package com.zhengb.flink.study.datastream.window;

import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

/**
 * 滑动窗口sliding window demo
 *
 * @author zhengbo
 * @date 2020/1/6
 */
@Slf4j
public class SlidingWindowDemo {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.socketTextStream("10.0.10.36", 9999).flatMap(
                new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {

                        String[] split = value.split(",");
                        for (String s : split) {
                            if (s.length() > 0) {
                                out.collect(new Tuple2<>(s, 1));
                            }
                        }
                    }

                }).keyBy(0).timeWindow(Time.seconds(10), Time.seconds(5)).sum(1).addSink(
                new SinkFunction<Tuple2<String, Integer>>() {
                    @Override
                    public void invoke(Tuple2<String, Integer> value, Context context) throws Exception {
                        log.info("sink word count data:{}", value);
                    }
                });

        env.execute("SlidingWindowDemo");

    }
}
